import React from 'react'
import style from './user_area.module.scss'
import { connect } from 'react-redux';
import { switch_loading } from '../../actions/index';
import { userProps } from '../../interface/user'
import { RouteComponentProps  } from 'react-router-dom'
import { Form, Button, DatePicker, Select, Table, Pagination, message } from 'antd';
import locale from 'antd/es/date-picker/locale/zh_CN'
import { userAreaList, userAreaListExport } from '../../server/api'
import { PAGE_SIZE, DATE_FORMAT } from '../../config/config'
import moment from 'moment'
import { DistrictItem } from '../../interface/common'

import districtList from '../../assets/district.json'

const { Option } = Select;
const { RangePicker } = DatePicker;
interface Props {
  user: userProps,
  isShowLoading: Boolean,
  dispatch: Function
}

class UseArea extends React.Component<RouteComponentProps & Props> {

  state = {
    pageno: 1,
    pagesize: PAGE_SIZE,
    startTime: 0,
    endTime: 0,
    type: 0,
    total: 0,
    list: [],
    exportParam: {},
    districtList: [],
    provinceList: [],
    cityList: [],
    province: '浙江',
	provinceCode: '0',
    city: '全部',
    cityCode: '0'
  }

  componentDidMount () {
    this.getSelectList()
  }

  private handleSubmit () {
    this.setState({
      pageno: 1,
      list: []
    })
    this.getList()
  }

  getCityList (code: string) {
    let list: any = []
    districtList.forEach((item: any) => {
      if (item.parentCode === code) {
        list.push(item)
      }
    })
    return list
  }

  async getSelectList () {
    let province = ''
    const provinceList: any = []
    let code = ''
    districtList.forEach((item: DistrictItem) => {
      if (item.name === '浙江省') {
        province = item.name
        code = item.code
      }
      if (+item.level === 1) {
        provinceList.push(item)
      }
    })
    let cityList = this.getCityList(code)
    this.setState({
      province: province,
	  provinceCode: code,
      provinceList,
      cityList
    }, () => {
      this.getList()
    })
  }

  private async getList () {

    let params = {
      pageNo: this.state.pageno,
      pageSize: this.state.pagesize,
      startTime: this.state.startTime,
      endTime: this.state.endTime,
      provinceCode: this.state.provinceCode,
      townCode: this.state.cityCode
    }
    if (params.pageNo  === 1) {
      this.setState({
        exportParam: params
      })
    }
    this.props.dispatch(switch_loading({show: true}))
    let res = await userAreaList(params)
    this.props.dispatch(switch_loading({show: false}))
    if (res.success === 'true') {
      res.info.userAreaList.forEach((item: any, index: number) => {
        item.key = index
        item.days_ = moment(item.days).format(DATE_FORMAT)
        for (let i = 0; i < districtList.length; i++) {
          if (item.provinceCode + '' === districtList[i].code + '') {
            item.province = districtList[i].name
            break
          }
        }
        for (let i = 0; i < districtList.length; i++) {
          if (item.townCode + '' === districtList[i].code + '') {
            item.town = districtList[i].name
            break
          }
        }
      })
      this.setState({
        total: res.info.count,
        list: res.info.userAreaList
      })
    } else {
      message.error(res.msg)
    }
  }

  private onDateChange (date: any) {
    this.setState({
      startTime: date.length > 0 ? new Date(date[0].format('YYYY/MM/DD') + ' 00:00:00').getTime() : 0,
      endTime: date.length > 0 ? new Date(date[1].format('YYYY/MM/DD') + ' 00:00:00').getTime() : 0
    })
  }

  private sourceChange (type: any) {
    this.setState({
      type
    })
  }

  private provinceChange(name: string) {
    let code: any = ''
    this.state.provinceList.forEach((item: DistrictItem) => {
      if (item.name === name) {
        code = item.code
      }
    })
    const cityList = this.getCityList(code)
    this.setState({
      province: name,
	  provinceCode: code,
      cityList,
      city: '全部',
      cityCode: 0
    }, () => {
      
    })
  }

  private cityChange(city: string) {
    let cityCode = ''
    this.state.cityList.forEach((item: any) => {
      if (item.name === city) {
        cityCode = item.code
      }
    })
    this.setState({
      city,
      cityCode
    })
  }

  private pageinChange (pageno: number) {
    this.setState({
      pageno
    }, () => {
      this.getList()
    })
  }

  private showSizeChange (current: number, pagesize: number) {
    this.setState({
      pageno: 1,
      pagesize
    }, () => {
      this.getList()
    })
  }

  private async exportList () {
    await userAreaListExport(this.state.exportParam)
  }

  render () {
    const { list, pageno, total, provinceList, cityList, pagesize, province, city } = this.state
    const columns = [
      {
        title: '时间',
        dataIndex: 'days_',
        key: 'days_',
        // eslint-disable-next-line
        // render: (text: string) => <a>{text}</a>,
      },
      {
        title: '省份',
        dataIndex: 'province',
        key: 'province',
      },
      {
        title: '市',
        dataIndex: 'town',
        key: 'town',
      },
      {
        title: '活跃用户数',
        dataIndex: 'headCount',
        key: 'headCount',
      }
    ];
    return (
      <div className='user-duration page'>
        <Form layout="inline" onSubmit={this.handleSubmit.bind(this)} className='search'>
          <Form.Item label="时间选择">
            <RangePicker locale={locale} onChange={this.onDateChange.bind(this)} placeholder={['开始时间', '结束时间']} format='YYYY-MM-DD'/>
          </Form.Item>
          <Form.Item label="地址选择">
            {
              // 必须选中一个省，没有全选
            }
            <Select showSearch value={province} style={{ width: 120 }} onChange={this.provinceChange.bind(this)}>
              {
                provinceList.map((item: DistrictItem) => {
                  return <Option key={item.code} value={item.name}>{item.name}</Option>
                })
              }
            </Select>
            <Select className={style.city} value={city} showSearch style={{ width: 120 }} onChange={this.cityChange.bind(this)}>
              <Option key='-1' value='全部'>全部</Option>
              {
                cityList.map((item: DistrictItem) => {
                  return <Option key={item.code} value={item.name}>{item.name}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary"  onClick={this.handleSubmit.bind(this)}>
              搜索
            </Button>
            <Button type="primary" onClick={this.exportList.bind(this)} className='export-btn'>
              导出
            </Button>
          </Form.Item>
        </Form>
        <Table className='table' columns={columns} dataSource={list} pagination={false}/>
        <Pagination className='pagination' current={pageno} total={ total } onShowSizeChange={this.showSizeChange.bind(this)}  onChange={this.pageinChange.bind(this)} pageSize={pagesize} showSizeChanger showQuickJumper showTotal={() => { return `共${total}条数据`}} />
      </div>
    )
  }
}

interface stateType {
  user: userProps,
  isShowLoading: Boolean
}

export default connect(
  (state: stateType) => ({
    user: state.user,
    isShowLoading: state.isShowLoading
  })
)(UseArea)